<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'

import { useProductSpecificationsListByProductId } from '@fl/api/fit-old-api'
import { SearchDescriptions, SearchTable } from '@fl/components'
import { ElButton } from 'element-plus'
import { cloneDeep } from 'lodash-es'

import Add from './add.vue'

const emits = defineEmits(['addSpecificationToTable', 'deleteSpecificationToTable'])
const specificationDetail = ref<any>({})
const dialogVisible = ref(false)
const specificationId = ref()

const childAdd = ref<InstanceType <typeof Add> | null>(null)
const productId = defineModel<string>('productId', { required: true })
console.log('table：productId', productId.value)

// 规格列表
const records = ref([])
const { data: specificationList, isLoading, refetch: specificationListRefetch } = useProductSpecificationsListByProductId(productId)
watchEffect(() => {
    if (specificationList.value)
        records.value = specificationList.value
})

const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const tableRef = ref()
const gridOptions = reactive<VxeGridProps>({
    align: 'center',
    columnConfig: {
        resizable: true,
    },
    columns: [
        // { type: 'checkbox', width: 50 },
        { field: 'formName', title: '规格名称' },
        { field: 'introduce', title: '规格介绍' },
        { field: 'remark', title: '备注' },
        { field: 'sort', title: '排序' },
        { field: 'price', title: '产品价格（元）' },
        { field: 'isDeleted', title: '是否删除' },
        { field: 'operate', fixed: 'right', slots: { default: 'opreate' }, title: '操作', width: '200' },
    ],
    data: records,
    editConfig: {
        mode: 'row',
        showStatus: true,
        trigger: 'manual',
    },
    height: 550,
    keepSource: true,
    showOverflow: true,
    toolbarConfig: {
        slots: {
            buttons: 'toolbar_buttons',
        },
    },
})

const specificationColumns: PlusColumn[] = [
    {
        descriptionsItemProps: {
            span: 1,
        },
        label: '规格名称:',
        prop: 'formName',
        width: 180,
    },
    {
        descriptionsItemProps: {
            span: 3,
        },
        label: '规格介绍:',
        prop: 'introduce',
        width: 180,
    },
    {
        descriptionsItemProps: {
            span: 1,
        },
        label: '排序:',
        prop: 'sort',
        width: 180,
    },
    {
        descriptionsItemProps: {
            span: 3,
        },
        label: '是否删除:',
        prop: 'isDeleted',
        width: 180,
    },
    {
        descriptionsItemProps: {
            span: 3,
        },
        label: '备注:',
        prop: 'remark',
        width: 180,
    },
    {
        descriptionsItemProps: {
            span: 3,
        },
        label: '产品价格:',
        prop: 'price',
        width: 180,
    },
    {
        descriptionsItemProps: {
            span: 3,
        },
        label: '产品图片:',
        prop: 'fileUrl',
        slot: 'fileUrl',
        width: 180,
    },
]

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
}

// 编辑规格
function editHandle(row) {
    specificationId.value = row.id
    specificationDetail.value = cloneDeep(row)
    unref(childAdd)!.handleAddOpen('edit')
}

// 查看规格
function viewHandle(row) {
    specificationId.value = row.id
    console.log('table viewHandle', row)
    specificationDetail.value = cloneDeep(row)
    dialogVisible.value = true
}

// 删除规格
function deleteRow(row: any) {
    const i = records.value.findIndex((val) => {
        return val.tempKey === row.tempKey
    })
    records.value.splice(i, 1)
    console.log('table delete', records)

    // 告诉父级
    emits('deleteSpecificationToTable', row)
}

// 新增规格
function addHandle() {
    unref(childAdd)!.handleAddOpen('add')
}

// 新增产品（无productId）时，传入的规格item
function addSpecification(item) {
    const _item = {
        ...item,
        tempKey: `${new Date().getTime()}`.substring(6),
    }
    console.log('table新增规格data', _item)
    records.value.push(_item)
    // 传给父级
    emits('addSpecificationToTable', _item)
}

// 编辑产品、增删规格时，刷新列表
function refreshSpecificationData() {
    console.log('编辑产品-新增规格-准备刷新')
    specificationListRefetch()
}
</script>

<template>
    <div class="mt-60 text-16 font-500">
        产品规格
    </div>

    <ElSkeleton v-if="isLoading"
                animated
                class="mt-20"
    />

    <SearchTable v-else
                 v-bind="gridOptions"
                 ref="tableRef"
                 v-model:pager="tablePage"
                 row-class-name="table-row-style"
                 @page-change="handlePageChange"
    >
        <template #toolbar_buttons>
            <ElButton type="primary"
                      @click="addHandle"
            >
                <template #icon>
                    <div i-ep:plus />
                </template>
                新增
            </ElButton>

            <!-- <ElButton plain
                      type="primary"
            >
                导出
            </ElButton> -->
        </template>

        <template #opreate="{ row }">
            <div class="flex justify-center gap-20">
                <span class="cursor-pointer text-#86909C"
                      @click="viewHandle(row)"
                >查看
                </span>

                <span class="cursor-pointer text-#86909C"
                      @click="editHandle(row)"
                >编辑
                </span>

                <span class="cursor-pointer text-#F53639"
                      @click="deleteRow(row)"
                >删除</span>
            </div>
        </template>
    </SearchTable>

    <Add ref="childAdd"
         v-model:id="specificationId"
         v-model:productId="productId"
         :data="specificationDetail"
         @add-specification-data="addSpecification"
         @refresh-specification-data="refreshSpecificationData"
    />

    <el-dialog v-model="dialogVisible"
               title="规格详情"
               width="800"
    >
        <SearchDescriptions :columns="specificationColumns"
                            :data="specificationDetail"
        >
            <template #plus-desc-fileUrl="{ value }">
                <el-image style="width: 100px; height: 100px"
                          :src="value"
                          :preview-src-list="[value]"
                          fit="contain"
                />
            </template>
        </SearchDescriptions>
    </el-dialog>
</template>
